package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"user/api/request"
	"user/inits"
)

func WsFunc(context *gin.Context) {
	var upgrader = websocket.Upgrader{}
	c, err := upgrader.Upgrade(context.Writer, context.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		_, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		var request request.WsRequest
		err = json.Unmarshal(message, &request)
		if err != nil {
			ResponseError(c, 1000, "非法入参")
			continue
		}
		switch request.Cmd {
		case "send":
			go SendFunc(c, message)
		default:
			go ResponseError(c, 1001, "没有该方法")
		}
	}
}

func SendFunc(c *websocket.Conn, message []byte) {
	var request request.WsSendRequest
	err := json.Unmarshal(message, &request)
	if err != nil {
		ResponseError(c, 1000, "发送信息解析失败")
		return
	}
	toUserConn := inits.OnLineUser[request.Data.ToUserId]
	if toUserConn == nil {
		ResponseError(c, 1000, "用户不在线")
		return
	}
	toUserConn.WriteMessage(websocket.TextMessage, []byte(request.Data.Message))

	ResponseSuccess(c, "信息发送成功")
}

func ResponseError(c *websocket.Conn, code int, msg string) {
	response := request.WsResponse{
		Code: code,
		Msg:  msg,
	}
	marshal, err := json.Marshal(response)
	err = c.WriteMessage(websocket.TextMessage, marshal)
	if err != nil {
		log.Println("write:", err)
	}
}

func ResponseSuccess(c *websocket.Conn, data interface{}) {
	response := request.WsResponse{
		Code: 0,
		Msg:  "",
		Data: nil,
	}
	marshal, err := json.Marshal(response)
	err = c.WriteMessage(websocket.TextMessage, marshal)
	if err != nil {
		log.Println("write:", err)
	}
}
